package com.shxc.smarttrade.old.modal;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;

import org.xchris.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/5/22.
 */

public class ObtainRealTimeQuote implements IMainActivity {

    @Override
    public void getRealTimeQuoteDatas(String symbol, final IRequestServiceListener listener) {

        Map<String, Object> map = new HashMap<>();
        map.put("symbol", symbol);
        MyOkHttpUtils.getServiceDatas(x.app(),map, URLContents.HOME_FRAGMENT_REALTIMEQUOTE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                listener.faild("网络异常");
            }
            @Override
            public void success(String response, int id) {
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    listener.faild("数据异常");
                    return;
                }

                Gson gson = new Gson();

                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                String errCode = "";
                String errMsg = "";
                errCode = jsonObject.get("err_code").getAsString();
                errMsg = jsonObject.get("err_msg").getAsString();
                if (errCode.equals("0")) {
                    List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen = new ArrayList<>();
                    if (!jsonObject.get("data").getAsJsonObject().isJsonNull() && jsonObject.get("data").getAsJsonObject().isJsonObject()) {
                        JsonObject data = jsonObject.get("data").getAsJsonObject();
                        if (!data.get("quote").getAsJsonArray().isJsonNull() && data.get("quote").getAsJsonArray().isJsonArray()) {
                            JsonArray quote = data.get("quote").getAsJsonArray();
                            for (JsonElement je : quote) {
                                quoteBeen.add(gson.fromJson(je, RealTimeQuoteDatas.DataBean.QuoteBean.class));
                            }
                            listener.success(quoteBeen);
                        } else {
                            listener.faild("数据异常");
                        }

                    } else {
                        listener.faild("数据异常");
                    }

                } else {
                    listener.faild(errMsg);
                }
            }
        });
    }
}
